define(function (require, exports, module) {
    require("apps/lab-search.css");
    require("apps/easyui");

    var html = '<div class="box_tc_s">' +
        '<h3></h3><div data-id="exper" class="exper clearfix"></div>' +
        '<div data-id="condition" class="mt20"></div></div>';
    var cache = {};
    var condition = '<div data-id="{{id}}" class="condition-holder"><div class="conditions">加载中...</div></div>';
    var choosed = '{{#.}}<dl class="float-left ml10 dl-box clearfix" data-name="{{processName}}" data-ref="{{id}}">' +
        '<dt><img src="' + WE.contextPath + '/print{{processCover}}" class="wh64 float-left"/><dt>' +
        '<dd class="ml74"><span class="block" title="{{processName}}">{{_processName}}</span>' +
        '<span class="block mt5"><input type="checkbox" name="check_{{id}}" value="1" /></span>' +
        '</dl>{{/.}}';
    var ht = '<div class="attr-box">{{#.}}<h4 class="mt20" data-name="{{fieldName}}" data-type="{{fieldType}}"><span class="mr20">{{fieldName}}</span>' +
        '<input class="ml20" type="checkbox" name="{{id}}_checkbox" value="1" /></h4>' +
        '<div class="attr-li">属性加载中...</div>{{/.}}<div class="mt20"></div></div>';
    var description = "{{#.}}<h3>{{processName}}</h3>" +
        "{{#attrs}}<div class='condition-line'><span class='field-name'>{{fieldName}}</span><span class='field-name'>{{description}}</span></div>{{/attrs}}{{/.}}"

    function renderText(hoder, id) {
        hoder.html('<div><input type="radio" name="' + id + '" value="contain" checked/>包含<input data-id="attrValue" class="hydra-input-width"  />' +
            '<input class="ml20" type="radio" name="' + id + '" value="equal" />等于<input data-id="attrValue" class="hydra-input-width" disabled />' +
            '</div>');
    }

    function renderTimeOrNumber(holder, id) {
        holder.html('<div><input type="radio" name="' + id + '" value="less" checked/>小于<input data-id="attrValue" class="hydra-input-width"  />' +
            '<input class="ml20" type="radio" name="' + id + '" value="lessOrEqual" />小于或等于<input data-id="attrValue" class="hydra-input-width" data-options="disabled:true" /></div>' +
            '<div class="mt10"> <input type="radio" name="' + id + '" value="more" />大于<input data-id="attrValue" class="hydra-input-width" data-options="disabled:true" />' +
            '<input class="ml20" type="radio" name="' + id + '" value="moreOrEqual" />大于或等于<input data-id="attrValue" class="hydra-input-width" data-options="disabled:true" /></div>' +
            '<div class="mt10"><input type="radio" name="' + id + '" value="between" />在<input data-id="attrValue" class="hydra-input-width" data-options="disabled:true"/>' +
            '<span class="mlr20">到</span><input class="hydra-input-width" data-id="attrValue" data-options="disabled:true"/>之间</div>');
    }

    function renderDirectory(holder, id) {
        holder.html('<div>等于<select name="' + id + '" class="hydra-input-width"></select></div>');
    }

    var typeRender = {
        FIELD_TYPE_TIME: function (holder, id) {
            renderTimeOrNumber(holder, id);
            holder.find("input:text").datetimebox();
        },
        FIELD_TYPE_TEXTAREA: renderText,
        FIELD_TYPE_TEXT: renderText,
        FIELD_TYPE_NUM: function (holder, id) {
            renderTimeOrNumber(holder, id);
            holder.find("input:text").numberbox({
                precision: -1
            });
        },
        FIELD_TYPE_DIRECTORY: function (holder, id) {
            renderDirectory(holder, id);
            holder.find("select").combobox({
                mode: 'remote',
                valueField: 'dirValue',
                textField: 'dirValue',
                loadFilter: function (data) {
                    return data.content;
                },
                url: WE.contextPath + "/app/api/directory/list?dirGroup=" + this.fieldTypeParam,
                editable: false
            });
        }
    };

    var validateTypes = ["FIELD_TYPE_TIME", "FIELD_TYPE_TEXTAREA", "FIELD_TYPE_TEXT", "FIELD_TYPE_NUM", "FIELD_TYPE_DIRECTORY"];

    var typeDisabledOrAble = {
        FIELD_TYPE_TIME: function (input, status) {
            $(input).datetimebox({disabled: status});
        },
        FIELD_TYPE_TEXTAREA: function (input, status) {
            $(input).prop("disabled", status);
        },
        FIELD_TYPE_TEXT: function (input, status) {
            $(input).prop("disabled", status);
        },
        FIELD_TYPE_NUM: function (input, status) {
            $(input).numberbox({disabled: status});
        },
        FIELD_TYPE_DIRECTORY: function (input, status) {
            $(input).combobox({disabled: status});
        }
    };

    var typeValue = {
        FIELD_TYPE_TIME: function () {
            return $(this).datetimebox("getValue");
        },
        FIELD_TYPE_TEXTAREA: function (input) {
            return $(this).val();
        },
        FIELD_TYPE_TEXT: function (input) {
            return $(this).val();
        },
        FIELD_TYPE_NUM: function (input) {
            return $(this).numberbox("getValue");
        },
        FIELD_TYPE_DIRECTORY: function (input) {
            return $(this).combobox("getValue");
        }
    };

    function selectData(holder, data) {
        var table = holder.html(Mustache.render(ht, data)).children();
        var tdr = table.find("div.attr-li");
        for (var i = 0, l = data.length; i < l; i++) {
            typeRender[data[i].fieldType].call(data[i], tdr.eq(i), data[i].id);
            tdr.eq(i).find("input:radio").on("click", function () {
                var clo = $(this).closest(".attr-li"), type = clo.prev("h4").attr("data-type");
                var that = this;
                clo.find("[data-id=attrValue]").each(function () {
                    typeDisabledOrAble[type].call(that, this, true);
                });
                $(that).nextUntil("input:radio").filter("[data-id=attrValue]").each(function () {
                    typeDisabledOrAble[type].call(that, this, false);
                });
            })
        }
        table.find("input:checkbox").toggleButton({
            dataRef: {
                "0": "不检索",
                "1": "参与检索"
            },
            onCheck: function (value) {
                var pa = this.element.closest("h4").next();
                if (value == "1") {
                    pa.show();
                } else {
                    pa.hide();
                }
            }
        });
    }

    var typesRef = {
        "操作人员": "operator",
        "操作时间": "operateTime",
        "执行结果": "result"
    };
    var conditionRef = {
        "contain": "包含",
        "equal": "等于",
        "less": "小于",
        "lessOrEqual": "小于或等于",
        "more": "大于",
        "moreOrEqual": "大于或等于"
    };
    $.widget("custom.labSearch", {
        options: {
            queryPanel: $.noop
        },
        _addPanel: function (id, title) {
            var dom = this.warpperbox.find("[data-id=" + id + "]");
            if (dom.length) {
                this.warpperbox.find("[data-id=condition]").accordion("select", title);
            } else {
                require("plugins/jquery.mustache");
                var box = this.warpperbox.find("[data-id=condition]");
                box.accordion("add", {
                    title: title,
                    content: Mustache.render(condition, {id: id})
                });
                var _holder = this.warpperbox.find("[data-id=" + id + "]").find(".conditions");
                if (!cache[id]) {
                    $.getJSON(WE.contextPath + "/app/api/process/searchAttributes", {id: id}, function (data) {
                        cache[id] = [
                            {
                                fieldName: "操作人员",
                                id: $.utils.createUUID(6),
                                fieldType: "FIELD_TYPE_TEXT"
                            },
                            {
                                fieldName: "操作时间",
                                id: $.utils.createUUID(6),
                                fieldType: "FIELD_TYPE_TIME"
                            },
                            {
                                fieldName: "操作结果",
                                id: $.utils.createUUID(6),
                                fieldType: "FIELD_TYPE_TEXTAREA"
                            }
                        ];
                        for (var i = 0, l = data.length; i < l; i++) {
                            if (validateTypes.contains(data[i].fieldType)) {
                                cache[id].push(data[i]);
                            }
                        }
                        selectData(_holder, cache[id]);
                    })
                } else {
                    selectData(_holder, cache[id]);
                }
            }
        },
        _removePanel: function (id, title) {
            var box = this.warpperbox.find("[data-id=condition]");
            if (box.accordion("getPanel", title)) {
                box.accordion("remove", title);
            }
        },
        _renderCombo: function () {
            if (this._rendered) {
                return;
            }
            this._rendered = true;
            var that = this;
            that.warpperbox.find("[data-id=condition]").accordion();
            $.getJSON(WE.contextPath + "/app/api/process/list", function (data) {
                var results = [];
                for (var i = 0, l = data.length; i < l; i++) {
                    if (data[i].searchAble) {
                        data[i]._processName = data[i].processName.length > 5 ? data[i].processName.substr(0, 4) + "..." : data[i].processName;
                        results.push(data[i]);
                    }
                }
                that.warpperbox.find("[data-id=exper]").html(Mustache.render(choosed, results)).children().each(function () {
                    $(this).find("input:checkbox").toggleButton({
                        dataRef: {
                            "0": "不启用检索",
                            "1": "启用检索"
                        },
                        onCheck: function (value) {
                            var data = this.element.closest("dl").data();
                            if (value == "1") {
                                that._addPanel(data.ref, data.name)
                            } else {
                                that._removePanel(data.ref, data.name)
                            }
                        }
                    })
                })
            });
        },
        getData: function () {
            var v = this.form.val();
            if (v.length) {
                return JSON.parse(v);
            }
            return [];
        },
        _makeData: function () {
            var processes = [], titles = {};
            var panels = this.warpperbox.find("[data-id=condition]");
            for (var i = 0, l = panels.length; i < l; i++) {
                var panel = $(panels[i]);
                var id = panel.find(".condition-holder").attr("data-id");
                var process = {
                    id: panel.find(".condition-holder").attr("data-id"),
                    conditions: []
                };
                titles[process.id] = panel.find(".panel-title").html();
                panel.find(".attr-box>h4").each(function () {
                    if ($(this).find(":checkbox:checked").length > 0) {
                        var condition = {
                            attrName: $(this).attr("data-name")
                        };
                        var type = $(this).attr("data-type");
                        var attrValues = [];
                        if (type == 'FIELD_TYPE_DIRECTORY') {
                            condition.attrCondition = "equal";
                            var v = typeValue[type].call($(this).next().find("select"));
                            v = $.trim(v);
                            if (v.length > 0) {
                                attrValues.push(v);
                            }
                        } else {
                            var checkedRadio = $(this).next().find("input:radio:checked");
                            condition.attrCondition = checkedRadio.val();
                            checkedRadio.nextUntil("input:radio").each(function () {
                                if ($(this).is("input[data-id=attrValue]")) {
                                    var v = typeValue[type].call(this);
                                    v = $.trim(v);
                                    if (v.length > 0) {
                                        attrValues.push(v);
                                    }
                                }
                            });
                        }
                        condition.attrValue = attrValues.join(",");
                        condition.attrType = typesRef[condition.attrName] ? typesRef[condition.attrName] : "others";
                        condition.attrFieldType = type;
                        var valid = true;
                        if (condition.attrCondition == "between") {
                            valid = attrValues.length > 1;
                        } else {
                            valid = attrValues.length > 0;
                        }
                        if (valid) {
                            process.conditions.push(condition);
                        }
                    }
                });
                if (process.conditions.length) {
                    processes.push(process);
                }
            }
            this.labCondition.hide();
            if (processes.length) {
                this.labCondition.show();
                this.form.val(JSON.stringify(processes));
                var des = [];
                for (var i = 0, l = processes.length; i < l; i++) {
                    var process = processes[i];
                    var de = {
                        processName: titles[process.id]
                    };
                    de.attrs = [];
                    for (var j = 0; j < process.conditions.length; j++) {
                        var condition = process.conditions[j];
                        de.attrs.push({fieldName: condition.attrName});
                        if (condition.attrCondition == 'between') {
                            var v = condition.attrValue.split(",");
                            de.attrs[j].description = "在“" + v[0] + "”到“" + v[1] + "”之间";
                        } else {
                            de.attrs[j].description = conditionRef[condition.attrCondition] + "“" + condition.attrValue + "”";
                        }
                    }
                    des.push(de);
                }
                this.labCondition.html(Mustache.render(description, des));
            }
        },
        _create: function () {
            var that = this;
            this.warpperbox = $("<div class='condition-box'></div>").appendTo("body").html(html).dialog({
                title: "工件工艺参数检索",
                closed: true,
                height: 500,
                width: 800,
                buttons: [
                    {
                        text: "确定",
                        handler: function () {
                            that.warpperbox.dialog("close");
                            that._makeData();
                        }
                    }
                ]
            });
            this.element.wrap("<div class='lab-search'></div>");
            this.labCondition =
                this.options.labCondition ? this.options.labCondition :
                    $("<div class='lab-condition-area' style='display: none'></div>").insertAfter(this.element);
            this.form = $("<textarea class='lab-condition-form' style='display: none'></textarea>").insertBefore(this.element);
            this.element.linkbutton({
                onClick: function () {
                    that._renderCombo();
                    that.warpperbox.dialog("open");
                }
            })
        }
    });
});